let authorizeBusiness = module.exports = {};


const Promise = require('bluebird');
const co = require('co');
const config = require('config');
const _ = require('underscore');
let OAuth = require('wechat-oauth');
const errinfo = require('../errinfo');
const responseJsonUtils = require('../utils/responseJsonUtils');


/**
 * request login
 */
authorizeBusiness.requestLoginSuc = function (req, res, next) {
    req.query.redirectUrl = req.query.redirectUrl || 'www.huipengchang.com';
    req.query.scope = req.query.scope || 'snsapi_userinfo';

    let wechatOAuthClient = new OAuth(config.wechat.appID, config.wechat.appSecret, function (openid, callback) {
        // 传入一个根据openid获取对应的全局token的方法
        // 在getUser时会通过该方法来获取token
        Token.getToken(openid, callback);
    }, function (openid, token, callback) {
        // 持久化时请注意，每个openid都对应一个唯一的token!
        Token.setToken(openid, token, callback);
    });

    let loginUrl = wechatOAuthClient.getAuthorizeURL(req.query.redirectUrl, req.query.state, req.query.scope);

    res.redirect(loginUrl);
};


/**
 * wechat get user by access token
 */
// check input
authorizeBusiness.checkInput = function (req, res, next) {

    if (_.isUndefined(req.query.code) || _.isNull(req.query.code)) {
        next(responseJsonUtils.json(errinfo.wechat.codeEmpty));
        return;
    }
    next();
};
// access wechat
authorizeBusiness.userInfo = function (req, res, next) {
    let wechatOAuthClient = new OAuth(config.wechat.appID, config.wechat.appSecret, function (openid, callback) {
        // 传入一个根据openid获取对应的全局token的方法
        // 在getUser时会通过该方法来获取token
        Token.getToken(openid, callback);
    }, function (openid, token, callback) {
        // 持久化时请注意，每个openid都对应一个唯一的token!
        Token.setToken(openid, token, callback);
    });
    co.wrap(getWechatUserInfo)(wechatOAuthClient, req)
        .then(function (result) {
            // console.log(result);
            req.user = result;
            next();
        }, function (err) {
            // console.log(err);
            next(err);
        });

};

function *getWechatUserInfo(wechatOAuthClient, req) {
    if (!wechatOAuthClient || !req) {
        Promise.reject();
        return;
    }
    let accessTokenInfo = yield getAccessToken(wechatOAuthClient, req.query.code);
    let userInfo = yield getUserInfo(wechatOAuthClient, accessTokenInfo.openid);

    return userInfo;
}
function getAccessToken(wechatOAuthClient, code) {
    return new Promise(function (resolve, reject) {
        if (!code || !wechatOAuthClient) {
            reject();
            return;
        }

        wechatOAuthClient.getAccessToken(code, function (err, result) {
            if (err && err instanceof Error) {
                reject(responseJsonUtils.json(errinfo.wechat.getAccessTokenError, err));
                return;
            }
            let accessToken = result.data.access_token;
            let openid = result.data.openid;
            resolve({
                accessToken: accessToken,
                openid: openid
            });
        });
    });
}
function getUserInfo(wechatOAuthClient, openid) {
    return new Promise(function (resolve, reject) {
        if (!openid || !wechatOAuthClient) {
            reject();
            return;
        }

        wechatOAuthClient.getUser(openid, function (err, result) {
            if (err) {
                reject(responseJsonUtils.json(errinfo.wechat.getUserError, err));
                return;
            }
            resolve(result);
        });
    });
}

// store user info
authorizeBusiness.storeUserInfo = function (req, res, next) {
    if (!req.user) {
        next(responseJsonUtils.json(errinfo.system.internalError));
        return;
    }
    req.user.from = 'wechat';
    let condition = {};
    if (req.user.unionid) {
        condition.unionid = req.user.unionid;
    } else if (req.user.openid) {
        condition.openid = req.user.openid;
    } else {
        next(responseJsonUtils.json(errinfo.system.internalError));
        return;
    }
    User.update(condition, req.user, {upsert: true}, function (err, updateResult) {
        if (err) {
            next(responseJsonUtils.json(errinfo.mongodb.internalError));
            return;
        }
        next();
    });
};
// suc
authorizeBusiness.suc = function (req, res, next) {
    // go to business router
    next();
};



